using MediatR;
using PiggyBankCashFlowApi.Delegate.command;
using PiggyBankCashFlowApi.Repo;
using PiggyBankCashFlowApi.Repo.Entity;

namespace PiggyBankCashFlowApi.Delegate.Handler;

public class QueryByUserIdAndPageHandler(
    CashFlowRepo repo,
    ILogger<QueryByUserIdAndPageHandler> logger)
    : IRequestHandler<QueryByUserIdAndPageCommand, List<CashFlowEntity>>
{
    public async Task<List<CashFlowEntity>> Handle(QueryByUserIdAndPageCommand request,
        CancellationToken cancellationToken)
    {

        if (request.UserIds == null)
        {
            throw new ArgumentException("Actual user id are null vs expected Not Null");
        }

        if (request.UserIds.Length < 1)
        {
            throw new ArgumentException($"Actual user id array size = {request.UserIds.Length} vs expected >=1");
        }

        if (request.UserIds.Any(id => id < 1))
        {
            throw new ArgumentException("User Id must be greater than 0");
        }
        
        if (request.Page < 1)
        {
            
            throw new ArgumentException($"Actual page = {request.Page} vs expected >1");
        }

        if (request.PageSize is < 1 or > 100)
        {
            throw new ArgumentException($"Actual page size = {request.PageSize} vs expected [1,100]");
        }

        var result = new List<CashFlowEntity>();
        result.AddRange(await repo.GetCashFlowByUserIdAsync(request.UserIds, request.Page, request.PageSize));
        return result;
    }
}